package me.huha.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 *	     类名: HttpClientUtils.java
 *    描述: 通用的Http请求
 *    作者: Yepx
 * 创建日期: 2017年2月13日 下午5:33:11
 */
public class HttpClientUtils {
    
	private static Logger logger = Logger.getLogger(HttpClientUtils.class);
	private static int requestTime = 500; //请求时间
	private static int responseTime = 500; //响应时间
	/**
	 * 编码格式。发送编码格式统一用UTF-8
	 */
	private static String ENCODING = "UTF-8";
	
	/**
	 * 基于HttpClient 4.3的通用POST方法
	 * @param url  提交的URL
	 * @param paramsMap 提交<参数，值>Map
	 * @return 提交响应
	 */
	public static String post(String url, Map<String, String> paramsMap) {
		
		//获取配置中心配置的资源。
		/*try{
			String requestTimeStr = Diamond.getConfig("me.huha.util.HttpClientUtils.requestTime", "mtop", 1000);
			String responseTimeStr = Diamond.getConfig("me.huha.util.HttpClientUtils.responseTime", "mtop", 1000);
			
			if(StringUtils.isNotBlank(requestTimeStr)){
				requestTime = Integer.parseInt(requestTimeStr);
			}
			if(StringUtils.isNotBlank(requestTimeStr)){
				responseTime = Integer.parseInt(responseTimeStr);
			}
		}catch(Exception e){
			logger.error(e);
			logger.error("获取配置中心的配置信息出错。");
		}*/
		
		
		CloseableHttpClient client = HttpClients.createDefault();
		String responseText = "";
		CloseableHttpResponse response = null;
		try {

			HttpPost method = new HttpPost(url);
			if (paramsMap != null) {
				List<NameValuePair> paramList = new ArrayList<NameValuePair>();
				for (Map.Entry<String, String> param : paramsMap.entrySet()) {
					NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
					paramList.add(pair);
				}
				method.setEntity(new UrlEncodedFormEntity(paramList, ENCODING));
			}

			//设置请求响应时间
			RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(requestTime).setConnectionRequestTimeout(requestTime).setSocketTimeout(responseTime).build();
			method.setConfig(requestConfig);
			
			response = client.execute(method);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				responseText = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			try {
				response.close();
			} catch (Exception e) {
				logger.error("", e);
			}
		}
		return responseText;
	}
}
